package org.com.ashen.service.service.smspinmanage;

import org.apache.commons.codec.digest.DigestUtils;
import org.com.ashen.client.service.ISMSPINService;
import org.com.ashen.common.common.HttpResult;
import org.com.ashen.common.common.smspin.SMSPINDTO;
import org.com.ashen.common.common.smspin.SMSPINRedDTO;
import org.com.ashen.common.common.smssendlog.SMSSendLogDTO;
import org.com.ashen.dal.dataobject.SMSPIN;
import org.com.ashen.dal.dataobject.Users;
import org.com.ashen.service.dao.SMSPINDao;
import org.com.ashen.service.dao.UsersDao;
import org.com.ashen.service.util.CodeUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service("sMSPINService")
public class SMSPINServiceImpl implements ISMSPINService {

    @Resource(name = "sMSPINDao")
    SMSPINDao sMSPINDao;

    @Resource(name = "usersDao")
    private UsersDao usersDao;

    @Override
    public HttpResult<SMSPINDTO> updatePin(SMSPINRedDTO record) {
        SMSPINDTO smspindto = new SMSPINDTO();
        if(record == null){
            return HttpResult.failedResult(smspindto,"传入内容不能为空");
        }
        String userId = record.getUserId();
        if(userId.equals("")){
            return HttpResult.failedResult(smspindto,"用户不能为空");
        }
        Users users = usersDao.getUserByLoginId(userId);
        if(users==null){
            return HttpResult.failedResult(smspindto,"用户不存在");
        }
        String APPSecret = users.getAppsecret();
        String privateAPPSecret = record.getPrivateAPPSecret();
        String statusTime = record.getSendTime();
        String tempAppSecret = CodeUtil.toStr(DigestUtils.md5(userId + APPSecret + statusTime));
        if(!tempAppSecret.equals(privateAPPSecret)){
            return HttpResult.failedResult(smspindto,"用户验证不通过");
        }

        SMSPIN smspin = new SMSPIN();
        smspin.setStatus("1");
        smspin.setMobile(record.getMobile());
        smspin.setPin(record.getPin());
        int num =  sMSPINDao.updateByPrimaryKeySelective(smspin);

        if(num > 0){
            smspindto.setStatus("SUCCESS");
            return HttpResult.successResult(smspindto);
        }
        smspindto.setStatus("FAIL");
        return HttpResult.failedResult(smspindto,"验证不通过");
    }
}
